package com.mobilepay.moneypig.model.activity.search;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.address.AddressData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.PreferenceUtil;
import com.mobilepay.moneypig.utils.acache.ACache;
import com.mobilepay.moneypig.view.DividerLine;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xlm on 2017/8/18 0018
 */

public class ChooseActivity extends BaseActivity {

    private RelativeLayout mAddreshBack;
    private TextView mAddressType;
    private SmartRefreshLayout mAddressRefresh;
    private RecyclerView mAddreshRecycle;
    private List<AddressData.DataBean> dataBeanList;
    private AddreshAdapter addreshAdapter;
    private String pid = "";
    private String name = "";

    @Override
    protected void onGetIntent(Intent intent) {
        super.onGetIntent(intent);
        pid = getIntent().getStringExtra("pid");
        name = getIntent().getStringExtra("name");
    }

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_address);
    }

    @Override
    protected void initViews() {
        mAddreshBack = (RelativeLayout) findViewById(R.id.address_back);
        mAddressType = (TextView) findViewById(R.id.address_type);
        mAddressRefresh = (SmartRefreshLayout) findViewById(R.id.address_refresh);
        mAddreshRecycle = (RecyclerView) findViewById(R.id.address_recycle);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        setAdapter();
        getData();
    }

    @Override
    protected void onSetListener() {
        mAddreshBack.setOnClickListener(this);
        mAddressRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getData();
            }
        });
        mAddressRefresh.setEnableLoadmore(false);
        addreshAdapter.setAddressClickListener(new AddreshAdapter.OnAddressClickListener() {
            @Override
            public void onAddreshClick(String ppid, String name) {
                if ("0".equals(pid)) {
                    PreferenceUtil.setParam(getThis(), "pid", ppid);
                }
                Intent intent = new Intent();
                intent.putExtra("pid", ppid);
                intent.putExtra("name", name);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.address_back:
                finish();
                break;
        }
    }

    private void setAdapter() {
        dataBeanList = new ArrayList<>();
        addreshAdapter = new AddreshAdapter(this);
        addreshAdapter.setData(dataBeanList);
        mAddreshRecycle.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        DividerLine dividerLine = new DividerLine();
        dividerLine.setColor(Color.parseColor("#e6e6e6"));
        dividerLine.setSize(1);
        mAddreshRecycle.addItemDecoration(dividerLine);
        mAddreshRecycle.setAdapter(addreshAdapter);
    }

    private void getData() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        if ("0".equals(pid)) {
            mAddressType.setText("选择省");
            param.add("model", "areas1");
            param.add("pid", pid);
        } else {
            if (!CommonUtil.isEmpty(pid)) {
                mAddressType.setText("选择市");
                param.add("model", "areas1");
                param.add("pid", pid);
            } else {
                mAddressType.setText("选择银行");
                param.add("model", "bank1");
                try {
                    param.add("keyword", URLEncoder.encode(name, "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        showProgress("加载中");
        HttpUtils.getInstance().params(param).executeProviceGet(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                mAddressRefresh.finishRefresh();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                    String jsonString = null;
                    if ("0".equals(pid)) {
                        jsonString = ACache.get(App.getApp()).getAsString("province");
                    } else {
                        jsonString = ACache.get(App.getApp()).getAsString("city");
                    }
                    if (!CommonUtil.isEmpty(jsonString)) {
                        setCityData(jsonString);
                    }
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                mAddressRefresh.finishRefresh();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        setCityData(string);
                        if ("0".equals(pid)) {
                            ACache.get(App.getApp()).put("province", string);
                        } else {
                            ACache.get(App.getApp()).put("city", string);
                        }
                    }
                }
            }
        });
    }

    private void setCityData(String string) {
        AddressData addressData = GsonUtil.GsonToBean(string, AddressData.class);
        List<AddressData.DataBean> beanList = addressData.getData();
        if (dataBeanList.size() != 0) {
            dataBeanList.clear();
        }
        dataBeanList.addAll(beanList);
        addreshAdapter.setData(dataBeanList);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                addreshAdapter.notifyDataSetChanged();
            }
        });
    }

    private static class AddreshAdapter extends RecyclerView.Adapter<AddreshViewHolder> {

        private Context context;
        private List<AddressData.DataBean> list;
        private LayoutInflater inflater;

        public AddreshAdapter(Context context) {
            this.context = context;
            inflater = LayoutInflater.from(context);
        }

        private void setData(List<AddressData.DataBean> list) {
            this.list = list;
        }

        @Override
        public AddreshViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            return new AddreshViewHolder(inflater.inflate(R.layout.item_address, viewGroup, false));
        }

        @Override
        public void onBindViewHolder(AddreshViewHolder addreshViewHolder, int i) {
            final AddressData.DataBean dataBean = list.get(i);
            addreshViewHolder.mTextName.setText(dataBean.getName());
            addreshViewHolder.mTextName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onAddressClickListener.onAddreshClick(dataBean.getId(), dataBean.getName());
                }
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        public void setAddressClickListener(OnAddressClickListener onAddressClickListener) {
            this.onAddressClickListener = onAddressClickListener;
        }

        private OnAddressClickListener onAddressClickListener;

        public interface OnAddressClickListener {
            void onAddreshClick(String ppid, String name);
        }
    }

    private static class AddreshViewHolder extends RecyclerView.ViewHolder {
        private TextView mTextName;

        public AddreshViewHolder(View itemView) {
            super(itemView);
            mTextName = (TextView) itemView.findViewById(R.id.text_address);
        }
    }

}
